<?php
/**
 * 用SimpleXML生成XML文档
 * User: ford
 * Date: 15-7-10
 * Time: 下午8:53
 */
//从创建根节点开始
$animals = new SimpleXMLElement('<animals/>');

$animals->{0} = "这是一个根元素的值，要保证有写入权限";

//下面把一个数组写进去，XML已经被JSON取代，了解一下吧
$dogs_array = array(
	array(
			'name'	=> 'snoopy',
			'color'	=> 'brown',
			'breed'	=> 'beagle cross'
	),
	array(
			'name'	=> 'jade',
			'color'	=> 'black',
			'breed'	=> 'lab cross'
	)
);
//添加dogs子元素
$dogs_xml = $animals->addChild('dogs');
//添加每个dog子元素
foreach ($dogs_array as $dog_array) {
	$dog = $dogs_xml->addChild('dog');
	foreach ($dog_array as $key => $value) {
		$tmp = $dog->addChild($key);
		$tmp->{0} = $value;
	}
}
//添加cats子元素
$cats_xml = $animals->addChild('cats');
$cats_array = array(
	array(
			'name'	=> 'teddy',
			'color'	=> 'brown',
			'breed'	=> 'tabby'
	)
);

foreach ($cats_array as $cat_array) {
	$cat = $cats_xml->addChild('cat');
	foreach ($cat_array as $key=>$value) {
		$tmp = $cat->addChild($key);
		$tmp->{0} = $value;
	}

}

$cats_xml = $animals->addChild('cats');

//接下来就可以生成XML文档了，另外，还需要注意编码问题
$animals->asXML('animals.xml');


//下面用DOMDocument生成一个输出格式良好的XML文档
$animals_dom = new DOMDocument('1.0');
$animals_dom->preserveWhiteSpace	= true;
$animals_dom->formatOutput			= true;
//返回DOMElement，导入上面用SimpleXML生成的$animals变量
$animals_dom_xml = dom_import_simplexml($animals);
$animals_dom_xml = $animals_dom->importNode($animals_dom_xml, true);
$animals_dom_xml = $animals_dom->appendChild($animals_dom_xml);
$animals_dom->save('animals_formatted.xml');


//现在来测试文档是否正确生成
var_dump(simplexml_load_file('animals_formatted.xml'));